
// #ifndef CONTROL_INL_H
// #define CONTROL_INL_H

#pragma once
#ifdef SPDLOG_HEADER_ONLY
#include <spdlog/control.h>
#endif

inline control::control()
{
  enable_control.store(false);
  init_control.store(false);
  arrival_frequency = true;
  thread_join = false;
  log_total.store(0,std::memory_order_relaxed);
  memset(&parameter,0x00,sizeof(controlParameter_t));
}

inline control::~control()
{
  thread_join = true;
  thread_control.join();
}

inline void control::init(bool enable,controlParameter & param){
  if (init_control.exchange(true)){
    return;
  }
  enable_control.store(enable);
  parameter.flush_level = param.flush_level > 6 ? 2 : param.flush_level;
  parameter.log_flow = param.log_flow;
  parameter.log_level = param.log_level > 6 ? 2 : param.log_level;
  parameter.log_frequency = param.log_frequency > MAX_LOG_FREQUENCY ? MAX_LOG_FREQUENCY : param.log_frequency;


  //判断是否启用线程
  if (enable_control.load() && (parameter.log_frequency > 0)){
    //启用频率线程
    thread_control = std::thread(&control::frequency, this);
    pthread_setname_np(thread_control.native_handle(), std::string("log_control").substr(0, 15).c_str());
  }
}

inline void control::frequency(){
  //计算睡眠时间,支持最大日志输出频率为5hz,时间单位ms
  uint32_t time_count = 1000 / parameter.log_frequency;
  uint16_t time_second = time_count / 1000;  //计算秒
  uint16_t time_millisecond = time_count - time_second * 1000; //计算毫秒

  while (true)
  {
    if (thread_join){
      break;
    }

    arrival_frequency = true;

    //进行睡眠,采用开机时间，以防系统时间跳变
    struct timespec request;

    request.tv_sec  = time_second;
    request.tv_nsec  = time_millisecond * 1000;
    clock_nanosleep(CLOCK_MONOTONIC,0,&request,nullptr);
  }
}
inline bool control::reset_log_frequency(){
  if (!enable_control.load() || (parameter.log_frequency == 0)){
    //未启用日志管控,默认每次重置成功
    return true;
  }
  //重置日志输出频率，规则当达到一个周期时，进行周期标识重置并返回重置成功，否则返回重置失败
  if (arrival_frequency){
    arrival_frequency = false;
    return true;
  }

  return false;
}

inline void control::log_total_add(int temp_size){
  log_total.fetch_add(temp_size,std::memory_order_relaxed);
}
// #endif